/*
 * Copyright 2012-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.context.properties.source;

import java.util.Collections;
import java.util.stream.Stream;

import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.ConfigurablePropertyResolver;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySource.StubPropertySource;
import org.springframework.core.env.PropertySources;
import org.springframework.core.env.PropertySourcesPropertyResolver;
import org.springframework.util.Assert;

/**
 * 提供对 {@link ConfigurationPropertySource ConfigurationPropertySources} 的访问。
 *
 * @author Phillip Webb
 * @since 2.0.0
 */
public final class ConfigurationPropertySources {

	/**
	 * {@link #attach(Environment)} 适配器中 {@link PropertySource} 的名称。
	 */
	private static final String ATTACHED_PROPERTY_SOURCE_NAME = "configurationProperties";

	private ConfigurationPropertySources() {
	}

	/**
	 * 创建一个新的 {@link PropertyResolver}，用于根据底层的 {@link PropertySources} 集合解析属性值。
	 * 提供一个支持 {@link ConfigurationPropertySource} 并经过优化的替代方案，
	 * 用于替代 {@link PropertySourcesPropertyResolver}。
	 *
	 * @param propertySources 要使用的 {@link PropertySource} 集合
	 * @return {@link ConfigurablePropertyResolver} 实现类
	 * @since 2.5.0
	 */
	public static ConfigurablePropertyResolver createPropertyResolver(MutablePropertySources propertySources) {
		return new ConfigurationPropertySourcesPropertyResolver(propertySources);
	}

	/**
	 * 判断指定的 {@link PropertySource} 是否是通过 {@link #attach(Environment)} 附加到
	 * {@link Environment} 的 {@link ConfigurationPropertySource}。
	 *
	 * @param propertySource 要测试的属性源
	 * @return 如果是附加的 {@link ConfigurationPropertySource}，则返回 {@code true}
	 */
	public static boolean isAttachedConfigurationPropertySource(PropertySource<?> propertySource) {
		return ATTACHED_PROPERTY_SOURCE_NAME.equals(propertySource.getName());
	}

	/**
	 * 将 {@link ConfigurationPropertySource} 支持附加到指定的 {@link Environment} 上。
	 * 会将环境中管理的每个 {@link PropertySource} 适配为一个 {@link ConfigurationPropertySource}，
	 * 并允许通过经典的 {@link PropertySourcesPropertyResolver} 调用，使用
	 * {@link ConfigurationPropertyName 配置属性名称} 进行解析。
	 * <p>
	 * 附加的解析器将动态跟踪底层 {@link Environment} 属性源的添加或移除操作。
	 * @param environment 源环境（必须是 {@link ConfigurableEnvironment} 的实例）
	 * @see #get(Environment)
	 */
	public static void attach(Environment environment) {
		Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
		MutablePropertySources sources = ((ConfigurableEnvironment) environment).getPropertySources();
		PropertySource<?> attached = getAttached(sources);
		if (attached == null || !isUsingSources(attached, sources)) {
			attached = new ConfigurationPropertySourcesPropertySource(ATTACHED_PROPERTY_SOURCE_NAME,
					new SpringConfigurationPropertySources(sources));
		}
		sources.remove(ATTACHED_PROPERTY_SOURCE_NAME);
		sources.addFirst(attached);
	}

	private static boolean isUsingSources(PropertySource<?> attached, MutablePropertySources sources) {
		return attached instanceof ConfigurationPropertySourcesPropertySource
				&& ((SpringConfigurationPropertySources) attached.getSource()).isUsingSources(sources);
	}

	static PropertySource<?> getAttached(MutablePropertySources sources) {
		return (sources != null) ? sources.get(ATTACHED_PROPERTY_SOURCE_NAME) : null;
	}

	/**
	 * 返回一组曾通过 {@link #attach(Environment)} 附加到 {@link Environment} 的
	 * {@link ConfigurationPropertySource} 实例。
	 *
	 * @param environment 源环境（必须是 {@link ConfigurableEnvironment} 的实例）
	 * @return 可迭代的配置属性源集合
	 * @throws IllegalStateException 如果没有附加任何配置属性源
	 */
	public static Iterable<ConfigurationPropertySource> get(Environment environment) {
		Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
		MutablePropertySources sources = ((ConfigurableEnvironment) environment).getPropertySources();
		ConfigurationPropertySourcesPropertySource attached = (ConfigurationPropertySourcesPropertySource) sources
				.get(ATTACHED_PROPERTY_SOURCE_NAME);
		if (attached == null) {
			return from(sources);
		}
		return attached.getSource();
	}

	/**
	 * 返回一个 {@link Iterable}，其中包含一个由指定的 Spring {@link PropertySource} 适配而成的
	 * 新的 {@link ConfigurationPropertySource}。
	 *
	 * @param source 要适配的 Spring 属性源
	 * @return 一个 {@link Iterable}，包含一个新适配的 {@link SpringConfigurationPropertySource}
	 */
	public static Iterable<ConfigurationPropertySource> from(PropertySource<?> source) {
		return Collections.singleton(ConfigurationPropertySource.from(source));
	}

	/**
	 * 返回一个 {@link Iterable}，其中包含从给定的 Spring {@link PropertySource PropertySources}
	 * 适配而来的新的 {@link ConfigurationPropertySource} 实例。
	 *
	 * <p>该方法会展开任何嵌套的属性源，并过滤掉所有 {@link StubPropertySource} 类型的属性源。
	 * 对于底层源的更新（即迭代器返回的源发生变化），将会被自动跟踪。
	 * 底层源应是线程安全的，例如 {@link MutablePropertySources}。
	 *
	 * @param sources 要适配的 Spring 属性源
	 * @return 一个 {@link Iterable}，包含新适配的 {@link SpringConfigurationPropertySource} 实例
	 */
	public static Iterable<ConfigurationPropertySource> from(Iterable<PropertySource<?>> sources) {
		return new SpringConfigurationPropertySources(sources);
	}

	private static Stream<PropertySource<?>> streamPropertySources(PropertySources sources) {
		return sources.stream().flatMap(ConfigurationPropertySources::flatten)
				.filter(ConfigurationPropertySources::isIncluded);
	}

	private static Stream<PropertySource<?>> flatten(PropertySource<?> source) {
		if (source.getSource() instanceof ConfigurableEnvironment) {
			return streamPropertySources(((ConfigurableEnvironment) source.getSource()).getPropertySources());
		}
		return Stream.of(source);
	}

	private static boolean isIncluded(PropertySource<?> source) {
		return !(source instanceof StubPropertySource)
				&& !(source instanceof ConfigurationPropertySourcesPropertySource);
	}

}
